##########################################################################################################################################
###### This is the file containing the merger regression results with betas based on daily data
###############################
# It creates Figure 2
# Please note that in some instances, the paper contains some formatting modifications
# such as a "log()" that is not automatically added here or that we present the negative
# of tsim, while most output here is generated for the positive

# This is just the final step. There are other code files that are used for data preparation
# This processed data are saved and loaded in this code

# set to your working directory:
setwd("C:\\Users\\Admin\\OneDrive\\Desktop\\Market Power and Systematic Risk - Data and Code")
getwd()


###################################
load("Mergers_with_SIC_NEW.RData")

Mergers_New$YearMonth = as.numeric(paste0(format(Mergers_New$Date.Effective.or.Unconditional,"%Y"),format(Mergers_New$Date.Effective.or.Unconditional,"%m")))
Mergers_New$YearMonth_ann = as.numeric(paste0(format(Mergers_New$Date.Announced,"%Y"),format(Mergers_New$Date.Announced,"%m")))
Mergers_New = Mergers_New[Mergers_New$Date.Announced>="1989-01-01",]

Mergers_New = Mergers_New[Mergers_New$Deal.Status == "Completed",]

Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Held.at.Announcement<10 | is.na(Mergers_New$Percentage.of.Shares.Held.at.Announcement),]

#only obtain mergers where at least 50 % of the Stock was Aquired:
Mergers_New = Mergers_New[Mergers_New$Percentage.of.Shares.Acquired.in.Transaction > 50 | is.na(Mergers_New$Percentage.of.Shares.Acquired.in.Transaction), ]


#Specify the M.A.Type
Mergers_New = Mergers_New[Mergers_New$M.A.Type == "Disclosed Dollar Value Deal" | 
                            Mergers_New$M.A.Type == "Undisclosed Dollar Value Deal",]

Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP != Mergers_New$Target.6.digit.CUSIP & !is.na(Mergers_New$Acquiror.6.digit.CUSIP),]

################################ Specifications #########################################################

Mergers_New = Mergers_New[apply(sapply(c("Acquire competitors technology/strategic assets",
                                         "Strengthen existing operations/expand presence in primary market",
                                         "Strengthen operations", "Create synergies", "Concentrate on core businesses/assets"), 
                                       grepl, Mergers_New$Purpose),1,any),]
##########################################################

load("Control_Panel.RData")

Panel_New<-Panel_New[order(Panel_New$YearMonth),]
Panel_New$Weight_Beta_M_lag=Panel_New$Weight_Beta_M
require(plyr)
Panel_New <- ddply( 
  Panel_New, .(PERMNO), transform,
  Weight_Beta_M_lag = c( NA, Weight_Beta_M[-length(Weight_Beta_M)] ) 
)

Panel_New$six_digit_cusip = substr(Panel_New$cusip,1,6)

Mergers_New = Mergers_New[Mergers_New$Acquiror.6.digit.CUSIP%in%Panel_New$six_digit_cusip,]
Mergers_New$Year=floor(Mergers_New$YearMonth/100)
Mergers_New$Year=Mergers_New$Year+1
Mergers_New$Year2=Mergers_New$Year+1

############################################
#########
Panel_New_all = merge(Panel_New,Mergers_New,by.x=c("YearMonth","six_digit_cusip"),by.y=c("YearMonth","Acquiror.6.digit.CUSIP"),all.x=T)

Panel_New_all$Merger_Dummy = ifelse(is.na(Panel_New_all$Date.Effective.or.Unconditional),999,0)
library(data.table)
setDT(Panel_New_all)
Panel_New_all = Panel_New_all[order(Panel_New_all$Time, decreasing = F),]

ExtAeND = function(x,days){
  #At this Point in Time a merger happened
  #print(length(x))
  a = which(x==1)
  if(length(a)>1){
    b = pmin(which(x==1) + days,length(x))
    c = mapply(seq,pmax(a-days,1),b,SIMPLIFY = F)
    for(i in 1:length(c)){
      if(length(c[[i]])==(2*days+1)){
        x[c[[i]]] = seq((-days),(days),by=1)
      }else if(length(c[[i]])<(2*days+1) & a[i]<(days+1)){
        x[c[[i]]] = seq((1-a[i]),(days),by=1)
      }else if(length(c[[i]])<(2*days+1) & length(x)<(a[i]+days+1)){
        x[c[[i]]] = seq((-days),(length(x)-a[i]),by=1)
      }
    }
  }
  return(x)
}

ExtAeND_Time = function(x,day_back,day_forward){
  Result = rep(NA,length(x))
  #At this Point in Time a merger happened
  a = pmax(which(x==0) - day_back, 1)
  if(length(a)>1){
    b = pmin(which(x==0) + day_forward, length(x))
    c = mapply(seq,a,b,SIMPLIFY=F)
    if(length(c)>1){
      if(any(diff(which(x==0))<=(2*day_forward))){
        for(i in which(c(100,diff(which(x==0)))<=(2*day_forward))){
          c[[i]] <- c[[i]][!(c[[i]]<=pmin(which(x==0)[i],c[[i]][1]+2*day_forward-c(100,diff(which(x==0)))[i]))]
        }
      }
      if(any(diff(which(x==0))<=(day_back))){
        for(i in which(c(diff(which(x==0)),100)<=(day_back))){
          c[[i]] <- c[[i]][!(c[[i]]>which(x==0)[i+1])]
        }
      }
    }
    if(length(c)>1){
      if(min(c[[2]])<max(c[[1]])){
        c[[1]] <- seq(from=min(c[[1]]),to=min(c[[2]])-1,by=1)
      }
    }
    
    for(i in length(which(x==0)):1){
      Result[which(x==0)] = 0
      if(length(Result[c[[i]][c[[i]]<which(x==0)[i]]])>=1)
        Result[c[[i]][c[[i]]<which(x==0)[i]]] = seq(from=-length(Result[c[[i]][c[[i]]<which(x==0)[i]]]),to=-1,by=1)
      
      if(length(Result[c[[i]][c[[i]]>which(x==0)[i]]])>=1)
        Result[c[[i]][c[[i]]>which(x==0)[i]]] = seq(to=length(Result[c[[i]][c[[i]]>which(x==0)[i]]]),from=1,by=1)
    }
    Result[which(x==0)] <-0
  }
  return(Result)
}


Panel_New_all[,Merger_Dummy:=ExtAeND_Time(Merger_Dummy,12,18),by=six_digit_cusip]



Panel_New_all$Merger_Dummy[is.na(Panel_New_all$Merger_Dummy)] = 999

#Conduct the Panel Regressions:
setDF(Panel_New_all)
Panel_New_all$year=Panel_New_all$year.x
Temp = Panel_New_all[,c("Time","YearMonth","year","NAICS","PERMNO","Beta_M","Weight_Beta_M","Shrinking_Beta_M","Weight_Beta_CF","Weight_Beta_DR",
                        "Weight_Beta_Down","Weight_Beta_Up","HHI","prodmktfluid","tnic3hhi","tnic3tsimm","Age","Momentum","Illiquidity","MktCap","Mkt_Book","Default_Spread",
                        "Financial_Leverage", "Operating_Leverage","Firm_size","InvestmentRates","ROE","Logat","Dividend_Dummy","q","I_Vol","Merger_Dummy")]#

library(lfe)
for(i in 1:dim(Temp)[2]){
  Temp[,i][Temp[,i] == Inf] = NA
  Temp[,i][Temp[,i] == -Inf] = NA
}
Temp = na.omit(Temp)

Temp$Merger_Dummy = as.factor(Temp$Merger_Dummy)

A = felm(Weight_Beta_M ~ Merger_Dummy + scale(log(Age)) + scale(Default_Spread) + Dividend_Dummy + scale(Financial_Leverage) + scale(log(Firm_size)) + scale(Illiquidity) + scale(InvestmentRates) + scale(I_Vol) +  
           scale(Logat) + scale(log(Mkt_Book)) + scale(Momentum)  + scale(Operating_Leverage) +  scale(q)  + scale(ROE)  | PERMNO + year | 0 | NAICS + year, data = Temp, cmethod="reghdfe")


############################# Do it beautifully ##################################

library(ggplot2)

day_forward = 18
day_back = 12
Time_Vector = c((-day_back+1):day_forward)
Interm = data.frame(pos=c(Time_Vector),Mean=coef(A)[1:(day_back+day_forward)],Down=c(coef(A)[1:(day_back+day_forward)]-1.645*summary(A)$coefficients[1:(day_back+day_forward),2]),
                    Up = c(coef(A)[1:(day_back+day_forward)]+1.645*summary(A)$coefficients[1:(day_back+day_forward),2]))
#Include a starting value:
Interm = rbind(c(-12,0,0,0),Interm)

ggplot(Interm,aes(x=pos,y=Mean,group=1)) + ggtitle('') + geom_ribbon(aes(x=pos, ymax=Up, ymin=Down),fill='grey',alpha=.15) + 
  geom_vline(xintercept = 0, colour = "red", linetype = 2) + geom_hline(yintercept = 0, colour = "blue", linetype = 2) +
  xlab("Time Relative to Merger (Months)") + ylab("Market Beta Merger Dummy") + theme_classic() + geom_line() + theme(axis.title=element_text(size=14))

ggsave("Mergerplot.pdf", width = 12, height = 6) 

